# -*- coding: utf-8 -*-
import scrapy
from scrapy.exceptions import IgnoreRequest
from scrapy.utils.project import get_project_settings
from datetime import datetime
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.model.items import Box
from zc_core.util.http_util import retry_request
from agshop.rules import *
from zc_core.spiders.base import BaseSpider


class OrderSpider(BaseSpider):
    name = 'order'
    # 常用链接
    order_list_url = 'https://agshop.delinzl.cn/api/unitenotice/pageQuery?noticeType=11&excludeType=4&current={}&size=10'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderSpider, self).__init__(batchNo=batchNo, *args, **kwargs)

    def start_requests(self):
        yield scrapy.Request(
            url=self.order_list_url.format(1),
            callback=self.parse_order_list,
            meta={
                'reqType': 'order_page',
                'page': 1
            },
            headers={
                'Metis-Tenant': '8dd10f97bc684b4fbc845c0b344883aa',
            },
            errback=self.error_back,
            dont_filter=True
        )

    def parse_order_list(self, response):
        page = response.meta.get('page', 1)
        order_list = parse_order_list(response)
        if order_list:
            yield Box('order', self.batch_no, order_list)
            self.logger.info('页数: page=%s' % page)
        else:
            self.logger.info('列表为空: page=%s' % page)
        if page == 1:
            total_pages = parse_order_page(response)
            self.logger.info('总页数: page=%s' % (total_pages))
            for i in range(2, total_pages + 1):
                yield scrapy.Request(
                    url=self.order_list_url.format(i),
                    callback=self.parse_order_list,
                    meta={
                        'reqType': 'order_page',
                        'page': i
                    },
                    headers={
                        'Metis-Tenant': '8dd10f97bc684b4fbc845c0b344883aa',
                    },
                    errback=self.error_back,
                    dont_filter=True
                )
